﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Ecng.Collections;
using StockSharp.BusinessEntities;
using StockSharp.AlfaDirect;

namespace StockSharp.Connectors.Alfa.Forms
{
	using System.Linq;

	using Ecng.Common;

	using StockSharp.Algo;
	using StockSharp.Algo.Candles;
	using StockSharp.Logging;

	public partial class TestForm : Form, ILogReceiver
	{
		ITrader _trader;
		Portfolio _portfolio;
		Security _security;
		Security _security2nd;
		Order _order;
		private readonly LogManager _logManager;
		private TestStrategy _strategy;
		private CandleSeries _token;

		public TestForm()
		{
			InitializeComponent();

			Name = "TestForm";

			Id = Guid.NewGuid();

			_logManager = new LogManager();
			_logManager.Sources.Add(this);
			_logManager.Listeners.Add(new DebugLogListener());
		}

		private void TestFormLoad(object sender, EventArgs e)
		{
			try
			{
				_trader = new AlfaTrader();
				_logManager.Sources.Add(_trader.To<BaseTrader>());
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to create AlfaTrader: " + ex.Message);
				return;
			}

			this.AddInfoLog("AlfaTrader successfuly created");

			_trader.Connected += OnConnected;
			_trader.Disconnected += OnDisconnected;
			_trader.ConnectionError += OnConnectionError;
			_trader.NewSecurities += OnNewSecurities;
			_trader.NewPortfolios += OnNewPortfolios;
			_trader.NewTrades += OnNewTrades;
			_trader.NewMyTrades += OnNewMyTrades;
			_trader.MarketDepthsChanged += OnMarketDepthsChanged;
			_trader.SecuritiesChanged += OnSecuritiesChanged;
			_trader.PortfoliosChanged += PortfoliosChanged;
			_trader.OrdersChanged += OrdersChanged;
			_trader.NewPositions += NewPositions;
			_trader.PositionsChanged += PositionsChanged;


			var trader = _trader.To<AlfaTrader>();

			trader.CandlesFinished += OnCandlesFinished;
			trader.CandlesStarted += OnCandlesStarted;
			trader.CandlesChanged += OnCandlesChanged;
		}

		# region Button Handlers

		private void ButtonConnectClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Connect()");

            var alfaTrader = _trader.To<AlfaTrader>();
		    
			if(checkBoxAutoLogin.Checked)
			{
                alfaTrader.Login = textBoxLogin.Text;
                alfaTrader.Password = textBoxPassword.Text;
			}

            _trader.Connect();
		}

		private void ButtonDisconnectClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Disconnect()");
			_trader.Disconnect();
		}

		private void ButtonIsConnectedClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::IsConnected: " + _trader.IsConnected);
		}

		private void ButtonStartExportClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::StartExport()");
			_trader.StartExport();
		}

		private void ButtonStopExportClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::StopExport()");
			_trader.StopExport();
		}

		private void ButtonPrintSecurityClick(object sender, EventArgs e)
		{
			if (_security != null)
			{
				this.AddInfoLog(PrintUtils.Log(_security));
			}
			else
			{
				this.AddErrorLog(textBoxSecurity.Text +  " is not received yet, failed to print");
			}
		}

		private void ButtonMarketTimeClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::MarketTime RTS: " + _trader.GetMarketTime(ExchangeBoard.Forts.Exchange));
		}

		private void ButtonPositionsClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Positions(): {0}", _trader.Positions.Count());

			foreach (var position in _trader.Positions)
			{
				this.AddInfoLog(PrintUtils.Log(position));
			}
		}

		private void ButtonGetMarketDepthClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::GetMarketDepth()");

			if (_security == null)
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet");
			}
			else
			{
				var md = _trader.GetMarketDepth(_security);
				this.AddInfoLog("BestAsk: " + md.BestAsk + ", BestBid: " + md.BestBid);
			}
		}

		private void ButtonRegisterSecurityClick(object sender, EventArgs e)
		{
			if (_security != null)
			{
				this.AddInfoLog("ITrader::RegisterSecurity()");
				_trader.RegisterSecurity(_security);
			}
			else
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet, failed to register security");
			}
		}

		private void ButtonUnRegisterSecurityClick(object sender, EventArgs e)
		{
			if (_security != null)
			{
				this.AddInfoLog("ITrader::UnRegisterSecurity()");
				_trader.UnRegisterSecurity(_security);
			}
			else
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet, failed to register security");
			}
		}

		private void ButtonPropMyTradesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::MyTrades");
			var trades = _trader.MyTrades;

			foreach (var myTrade in trades)
			{
				PrintUtils.Log(myTrade);
			}
		}

		private void ButtonRegisterQuotesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::RegisterQuotes");

			if (_security == null)
			{
				this.AddInfoLog(textBoxSecurity.Text +  " is not received yet");
			}
			else
			{
				_trader.RegisterMarketDepth(_security);
			}
		}

		private void ButtonUnRegisterQuotesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::UnRegisterQuotes");

			if (_security == null)
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet");
			}
			else
			{
				_trader.UnRegisterMarketDepth(_security);
			}
		}

		private void ButtonRegisterTradesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::RegisterTrades");

			if (_security == null)
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet");
			}
			else
			{
				_trader.RegisterTrades(_security);
			}
		}

		private void ButtonUnRegisterTradesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::UnRegisterTrades");

			if (_security == null)
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet");
			}
			else
			{
				_trader.UnRegisterTrades(_security);
			}
		}

		private void ButtonRegisterPortfolioClick(object sender, EventArgs e)
		{
			if (_portfolio == null)
			{
				this.AddErrorLog("Portfolio is not received yet, failed to register");
			}
			else
			{
				this.AddInfoLog("ITrader::RegisterPortfolio");
				_trader.RegisterPortfolio(_portfolio);
			}
		}

		private void ButtonUnRegisterPortfolioClick(object sender, EventArgs e)
		{
			if (_portfolio == null)
			{
				this.AddErrorLog("Portfolio is not received yet, failed to unregister");
			}
			else
			{
				this.AddInfoLog("ITrader::UnRegisterPortfolio()");
				_trader.UnRegisterPortfolio(_portfolio);
			}
		}

		private void ButtonPropPortfoliosClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Portfolios");

			var portfolios = _trader.Portfolios;

			foreach (var p in portfolios)
			{
				this.AddInfoLog(PrintUtils.Log(p));
			}
		}

		private void ButtonPropSecuritiesClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Securities");

			foreach (var sec in _trader.Securities)
			{
				this.AddInfoLog(PrintUtils.Log(sec));
			}
		}

		private void ButtonPropOrdersClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::Odrers");

			var orders = _trader.Orders;

			foreach (Order order in orders)
			{
				this.AddInfoLog(PrintUtils.Log(order));
			}
		}

		private void ButtonPrintSecurityDetailsClick(object sender, EventArgs e)
		{
			if (_security == null)
			{
				this.AddErrorLog(textBoxSecurity.Text + " is not received yet, failed to print details");
			}
			else
			{
				this.AddInfoLog(PrintUtils.LogDetails(_security));
			}
		}

		private void ButtonPrintPortfolioClick(object sender, EventArgs e)
		{
			if (_portfolio == null)
			{
				this.AddErrorLog("Portfolio is not received yet, failed to print");
			}
			else
			{
				this.AddInfoLog(PrintUtils.Log(_portfolio));
			}
		}

		private void ButtonBuyMarketClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Buy Market");

			var order = new Order
			{
			    Type = OrderTypes.Market,
			    Portfolio = _portfolio,
			    Security = _security,
			    Volume = 1,
			    Direction = OrderDirections.Buy
			};

			try
			{
				_trader.RegisterOrder(order);
			}
			catch(Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonSellMarketClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Sell Market");

			var order = new Order
			{
			    Type = OrderTypes.Market,
			    Portfolio = _portfolio,
			    Security = _security,
			    Volume = 1,
			    Direction = OrderDirections.Sell
			};

			try
			{
				_trader.RegisterOrder(order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonBuyLimitClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Buy Limit");

			_order = new Order
			{
				Type = OrderTypes.Limit,
				Portfolio = _portfolio,
				Security = _security,
				Price = Decimal.Parse(textBoxBuyLimitPrice.Text),
				Volume = textBoxVolumeBuyLimit.Text.To<int>(),
				Direction = OrderDirections.Buy,
				ExpiryDate = DateTime.Now.AddDays(1).AddHours(1)
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonSellLimitClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Sell Limit");

			_order = new Order
			{
				Type = OrderTypes.Limit,
				Portfolio = _portfolio,
				Security = _security,
				Price = Decimal.Parse(textBoxSellLimitPrice.Text),
				Volume = 1,
				Direction = OrderDirections.Sell
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonBuyStopClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Buy Stop");

			_order = new Order
			{
				Type = OrderTypes.Conditional,
				Portfolio = _portfolio,
				Security = _security,
				Volume = textBoxBuyStopVolume.Text.To<decimal>(),
				Direction = OrderDirections.Buy,
				Condition = new AlfaLimitOrderCondition
				{
					StopPrice = textBoxBuyStopPrice.Text.To<double>(),
					Slippage = Double.Parse(textBoxBuyStopSlippage.Text)
				}
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonSellStopClick(object sender, EventArgs e)
		{
			this.AddInfoLog("Sell Stop");

			_order = new Order
			{
				Type = OrderTypes.Conditional,
				Portfolio = _portfolio,
				Security = _security,
				Volume = textBoxSellStopVolume.Text.To<decimal>(),
				Direction = OrderDirections.Sell,
				Condition = new AlfaLimitOrderCondition
				{
					StopPrice = textBoxSellStopPrice.Text.To<double>(),
					Slippage = Double.Parse(textBoxSellStopSlippage.Text)
				}
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void ButtonReRegisterOrderClick(object sender, EventArgs e)
		{
			this.AddInfoLog("ReRegister Order(): id = " + _order.Id);

			_trader.ReRegisterOrder(_order, textBoxReRegisterOrderPrice.Text.To<decimal>(),
				textBoxReRegisterOrderVolume.Text.To<int>());
		}

		#endregion // Button Handlers

		# region AlfaTrader Action Handlers

		void OnConnected()
		{
			this.AddInfoLog("OnConnected()");
		}

		void OnDisconnected()
		{
			this.AddInfoLog("OnDisconnected()");
		}

		void OnConnectionError(Exception ex)
		{
			this.AddInfoLog("OnConnectionError(): " + ex.Message);
		}

		void OnNewSecurities(IEnumerable<Security> securities)
		{
			this.AddInfoLog("OnNewSecurities()");

			foreach (var sec in securities)
			{
				PrintUtils.Log(sec);

				if (sec.Id == textBoxSecurity.Text)
				{
					this.AddInfoLog("Found {0}", sec.Id);
					_security = sec;
				}
				else if(sec.Id == textBoxSecurity2nd.Text)
				{
					this.AddInfoLog("Found {0}", sec.Id );
					_security2nd = sec;
				}
			}
		}

		void OnNewPortfolios(IEnumerable<Portfolio> portfolios)
		{
			this.AddInfoLog("OnNewPortfolios()");

			foreach (var port in portfolios)
			{
				this.AddInfoLog("New portfolio: " + port.Name);

				this.AddInfoLog(PrintUtils.Log(port));

				if (_portfolio == null)
				{
					_portfolio = port;
				}
			}
		}

		void OnNewTrades(IEnumerable<Trade> newTrades)
		{
			this.AddInfoLog("OnNewTrades()");

			foreach (var trade in newTrades)
			{
				this.AddWarningLog(PrintUtils.Log(trade));
			}
		}

		private void OnNewMyTrades(IEnumerable<MyTrade> myTrades)
		{
			this.AddInfoLog("OnNewMyTrades");

			foreach (var trade in myTrades)
			{
				this.AddInfoLog(PrintUtils.Log(trade));
			}
		}

		void OnMarketDepthsChanged(IEnumerable<MarketDepth> depths)
		{
			this.AddInfoLog("OnMarketDepthsChanged");

			foreach (var depth in depths)
			{
				this.AddInfoLog(depth.Security.Code + ", " + depth.BestBid + ", " + depth.BestAsk);
			}
		}

		void OnSecuritiesChanged(IEnumerable<Security> securities)
		{
			this.AddInfoLog("OnSecuritiesChanged()");

			foreach (var security in securities)
			{
				this.AddInfoLog(PrintUtils.LogDetails(security));
			}
		}

		void PortfoliosChanged(IEnumerable<Portfolio> portfolios)
		{
			this.AddInfoLog("PortfoliosChanged()");

			foreach (Portfolio portfolio in portfolios)
			{
				this.AddInfoLog(PrintUtils.Log(portfolio));
			}
		}

		void OrdersChanged(IEnumerable<Order> orders)
		{
			this.AddInfoLog("OrdersChanged()");

			foreach (var order in orders)
			{
				PrintUtils.Log(order);

				if(_order != null && _order.TransactionId == order.TransactionId)
				{
					_order = order;
				}
			}
		}

		void NewPositions(IEnumerable<Position> positions)
		{
			this.AddInfoLog("NewPositions()");

			foreach (var position in positions)
			{
				this.AddInfoLog(PrintUtils.Log(position));
			}
		}

		void PositionsChanged(IEnumerable<Position> positions)
		{
			this.AddInfoLog("PositionsChanged()");

			foreach (var position in positions)
			{
				this.AddInfoLog(PrintUtils.Log(position));
			}
		}

		#endregion //  AlfaTrader Action Handlers

		public Guid Id
		{
			get; internal set;
		}

		ILogSource ILogSource.Parent
		{
			get { return null; }
		}

		public LogLevels LogLevel { get; set; }

		public DateTime CurrentTime { get; private set; }

		public INotifyList<ILogSource> Childs
		{
			get { return null; }
		}

		public event Action<LogMessage> Log;

		public void AddLog(LogMessage message)
		{
			Log.SafeInvoke(message);
		}

		private void OnCandlesChanged(CandleSeries token, IEnumerable<TimeFrameCandle> candles)
		{
			this.AddInfoLog("- OnCandlesChanged");

			foreach (var candle in candles)
			{
				this.AddInfoLog("Updated candle: {0}, O {1}, C {2}".Put(candle.CloseTime, candle.OpenPrice, candle.ClosePrice));
			}
		}

		private void OnCandlesStarted(CandleSeries token, IEnumerable<TimeFrameCandle> candles)
		{
			this.AddInfoLog("- OnCandlesStarted");

			foreach (var candle in candles)
			{
				this.AddInfoLog("New candle: {0}, O {1}".Put(candle.CloseTime, candle.OpenPrice));
			}
		}

		private void OnCandlesFinished(CandleSeries token, IEnumerable<TimeFrameCandle> candles)
		{
			if(_token != null && _token == token)
			{
				this.AddInfoLog("- OnCandlesFinished: {0}", token);

				foreach (var candle in candles)
				{
					this.AddInfoLog("Finished candle, close time: {0}, O {1}, H {2}, L {3} C {4}".Put(candle.CloseTime, candle.OpenPrice, candle.HighPrice,candle.LowPrice,  candle.ClosePrice));
				}				
			}
		}

		private void buttonRegisterCandles_Click(object sender, EventArgs e)
		{
			var trader = _trader.To<AlfaTrader>();

			trader.RegisterCandles(_security, AlfaTimeFrames.Minute1, _security.GetMarketTime() - TimeSpan.FromDays(1), out _token);
			//trader.RegisterCandles(_security, AlfaTimeFrames.Hour, _security.GetMarketTime() - TimeSpan.FromDays(1), out _token);

			this.AddInfoLog("Registered token: {0}", _token.ToString());
		}

		private void buttonUnRegisterCandles_Click(object sender, EventArgs e)
		{
			if(_token != null)
			{
				var trader = _trader.To<AlfaTrader>();	
				trader.UnRegisterCandles(_token);
			}
		}

		private void buttonCancelOrders_Click(object sender, EventArgs e)
		{
			var trader = (AlfaTrader)_trader;
			trader.CancelOrders(null, _portfolio, null, null, _security);
		}

		private void buttonStartLimitQuoting_Click(object sender, EventArgs e)
		{
			_strategy.StartLimitQuoting();
		}

		private void buttonCreateStrategy_Click(object sender, EventArgs e)
		{
			_strategy = new TestStrategy
			{
				Trader = _trader,
				Security = _security,
				Portfolio = _portfolio
			};

			_logManager.Sources.Add(_strategy);

			_trader.RegisterMarketDepth(_security);
			_trader.RegisterSecurity(_security);
			_trader.RegisterTrades(_security);
		}

		private void buttonStartStrategy_Click(object sender, EventArgs e)
		{
			_strategy.Start();
		}

		private void buttonSecurity2_Click(object sender, EventArgs e)
		{
			if (_security2nd != null)
			{
				this.AddInfoLog(PrintUtils.Log(_security2nd));
			}
			else
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet");
			}
		}

		private void buttonSecurityDetails2_Click(object sender, EventArgs e)
		{
			if (_security2nd == null)
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet");
			}
			else
			{
				this.AddInfoLog(PrintUtils.LogDetails(_security2nd));
			}
		}

		private void buttonRegisterTrades2_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::RegisterTrades");

			if (_security2nd == null)
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet");
			}
			else
			{
				_trader.RegisterTrades(_security2nd);
			}
		}

		private void buttonUnRegisterTrades2_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::UnRegisterTrades");

			if (_security2nd == null)
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet");
			}
			else
			{
				_trader.UnRegisterTrades(_security2nd);
			}
		}

		private void buttonRegisterQuotes2_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::RegisterQuotes");

			if (_security2nd == null)
			{
				this.AddInfoLog(textBoxSecurity2nd.Text + " is not received yet");
			}
			else
			{
				_trader.RegisterMarketDepth(_security2nd);
			}
		}

		private void buttonUnRegisterQuotes2_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("ITrader::UnRegisterQuotes");

			if (_security2nd == null)
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet");
			}
			else
			{
				_trader.UnRegisterMarketDepth(_security2nd);
			}
		}

		private void buttonRegisterSecurity2_Click(object sender, EventArgs e)
		{
			if (_security2nd != null)
			{
				this.AddInfoLog("ITrader::RegisterSecurity()");
				_trader.RegisterSecurity(_security2nd);
			}
			else
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet, failed to register security");
			}
		}

		private void buttonUnRegisterSecurity2_Click(object sender, EventArgs e)
		{
			if (_security2nd != null)
			{
				this.AddInfoLog("ITrader::UnRegisterSecurity()");
				_trader.UnRegisterSecurity(_security2nd);
			}
			else
			{
				this.AddErrorLog(textBoxSecurity2nd.Text + " is not received yet, failed to register security");
			}
		}

		private void buttonBuyLimitX5_Click(object sender, EventArgs e)
		{
			for (var i = 0; i < 5; ++i )
			{
				this.AddInfoLog("Buy Limit");

				var order = new Order
				{
					Type = OrderTypes.Limit,
					Portfolio = _portfolio,
					Security = _security,
					Price = Decimal.Parse(textBoxBuyLimitPrice.Text),
					Volume = textBoxVolumeBuyLimit.Text.To<int>(),
					Direction = OrderDirections.Buy
				};

				try
				{
					_trader.RegisterOrder(order);
				}
				catch (Exception ex)
				{
					this.AddErrorLog("Failed to register order: " + ex.Message);
				}	
			}
		}

		private void buttonBuyLimitAndCancel_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("Buy Limit and Cancel");

			var order = new Order
			{
				Type = OrderTypes.Limit,
				Portfolio = _portfolio,
				Security = _security,
				Price = Decimal.Parse(textBoxBuyLimitPrice.Text),
				Volume = textBoxVolumeBuyLimit.Text.To<int>(),
				Direction = OrderDirections.Buy
			};

			try
			{
				_trader.RegisterOrder(order);
				_trader.CancelOrder(order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog(ex.Message);
			}
		}

		private void buttonBuyLimitAndCancelX5_Click(object sender, EventArgs e)
		{
			for(var i = 0; i < 5; ++i)
			{
				this.AddInfoLog("Buy Limit and Cancel");

				var order = new Order
				{
					Type = OrderTypes.Limit,
					Portfolio = _portfolio,
					Security = _security,
					Price = Decimal.Parse(textBoxBuyLimitPrice.Text),
					Volume = textBoxVolumeBuyLimit.Text.To<int>(),
					Direction = OrderDirections.Buy
				};

				try
				{
					_trader.RegisterOrder(order);
					_trader.CancelOrder(order);
				}
				catch (Exception ex)
				{
					this.AddErrorLog(ex.Message);
				}
			}
		}

		private void buttonBuyMQS_Click(object sender, EventArgs e)
		{
			var offset = textBoxMqsOffset.Text.To<decimal>();
			_strategy.StartMarketQuoting(OrderDirections.Buy, offset);
		}

		private void buttonSellMQS_Click(object sender, EventArgs e)
		{
			var offset = textBoxMqsOffset.Text.To<decimal>();
			_strategy.StartMarketQuoting(OrderDirections.Sell, offset);
		}

		private void buttonBuySellMQSx5_Click(object sender, EventArgs e)
		{
			var offset = textBoxMqsOffset.Text.To<decimal>();
			_strategy.StartMarketQuotingTest(offset);
		}

		private void buttonBuyStopTarget_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("Buy Stop + Target");

			_order = new Order
			{
				Type = OrderTypes.Conditional,
				Portfolio = _portfolio,
				Security = _security,
				Volume = 1,
				Direction = OrderDirections.Buy,
				Condition = new AlfaTargetLimitOrderCondition
				{
					StopPrice = textBoxBuyStopTarget_Price.Text.To<double>(),
					Slippage = textBoxBuyStopTarget_Slippage.Text.To<double>(),
					TargetPrice = textBoxBuyStopTarget_Target.Text.To<double>()
				}
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void buttonSellStopTarget_Click(object sender, EventArgs e)
		{
			this.AddInfoLog("Sell Stop + Target");

			_order = new Order
			{
				Type = OrderTypes.Conditional,
				Portfolio = _portfolio,
				Security = _security,
				Volume = 1,
				Direction = OrderDirections.Sell,
				Condition = new AlfaTargetLimitOrderCondition
				{
					StopPrice = textBoxSellStopTarget_Price.Text.To<double>(),
					Slippage = textBoxSellStopTarget_Slippage.Text.To<double>(),
					TargetPrice = textBoxSellStopTarget_Target.Text.To<double>()
				}
			};

			try
			{
				_trader.RegisterOrder(_order);
			}
			catch (Exception ex)
			{
				this.AddErrorLog("Failed to register order: " + ex.Message);
			}
		}

		private void buttonGetPosition_Click(object sender, EventArgs e)
		{
			var position = _trader.GetPosition(_portfolio, _security);

			if(position != null)
			{
				this.AddInfoLog("Position {0}. Current: {1}. Blocked: {2}", position.Security, position.CurrentValue, position.BlockedValue);	
			}
			else
			{
				this.AddInfoLog("Position is Null");
			}
		}

		private void buttonCancelOrder_Click(object sender, EventArgs e)
		{
			if(_order != null)
			{
				this.AddInfoLog("Отмена ордера id {0}, tr id {1}", _order.Id, _order.TransactionId);

				_trader.CancelOrder(_order);
			}
		}
	}
}
